from flask import Flask,request
import os,base64
import pymysql
import time
import math
import random
import os
from flask_cors import CORS
conn=pymysql.connect(host="localhost",user="root",password="jiahui.1233",db="test111")
cursor=conn.cursor()
app=Flask(__name__)

img_root='http://127.0.0.2/WJH/img/'
user_err={"status":401,"message":"账号暂无权限,请重新登录"}
user_success={"status":200,"message":"操作成功"}
def test(user_token):
    sql = 'select id from user where user_token="{}"'.format(user_token)
    cursor.execute(sql)
    user_id = cursor.fetchone()
    if user_id:
        return {'state': True, 'id': user_id[0]}
    else:
        return {'state': False, 'id': ""}

# CORS(app, resources={r'/*': {"origins": "*"}})
@app.route('/login',methods=['post'])
def hello():
    english_list=['a','b','c','d','e','f','g','h','i','j','k','l','m','n']
    user=request.values.get('user')
    password=request.values.get('password')
    print(request,user,password)

    sql='select * from user where user="{}" and password = "{}" '.format(user,password)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    data=cursor.fetchall()
    print(data)
    dict1={}
    user_token=[]
    for i in range(10):
        user_token.append(random.choice(english_list))
    user_token=user.join(user_token)

    sql='UPDATE user set user_token="{}" where user="{}" and password = "{}"'.format(user_token,user,password)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    if(bool(data)):
        user1 = data[0]
        dict1['user_id']=user1[0]
        dict1['theme'] = user1[3]
        dict1['head_icon']=user1[4]
        dict1['name'] = user1[5]
        dict1['sex'] = user1[6]
        dict1['birthday'] = user1[7]
        dict1['Personal_signature'] = user1[8]
        dict1['user_token']=user_token

        return {"status":200,"data":dict1,"message":"登陆成功"}
    return {"status":400,"message":"登陆失败"}
@app.route('/getUserData',methods=['GET'])
def getUserData():
    user_token=request.args.get('user_token')
    user_data=test(user_token)
    if user_data['state']==False:
        return user_err
    sql='select * from user where id="{}"'.format(user_data['id'])
    print(sql)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    data=cursor.fetchall()
    print(data)
    dict1={}
    if(bool(data)):
        user1 = data[0]
        dict1['user_id']=user1[0]
        dict1['theme'] = user1[3]
        dict1['head_icon']=user1[4]
        dict1['name'] = user1[5]
        dict1['sex'] = user1[6]
        dict1['birthday'] = user1[7]
        dict1['Personal_signature'] = user1[8]
        dict1['user_token']=user_token

        return {"status":200,"data":dict1,"message":"登陆成功"}
    return {"status":400,"message":"登陆失败"}
@app.route('/add_user',methods=['POST'])
def add_user():
    id=math.floor(time.time())
    user=request.values.get("user")
    password = request.values.get("password")
    theme="none"
    head_icon="**"
    name=request.values.get("name")
    sex="男"
    birthday="1999-01-01"
    Personal_signature = ""
    conn.ping(reconnect=True)
    sql='select id from user where user = "{}"'.format(user)
    cursor.execute(sql)
    data=cursor.fetchone()
    print(bool(data))
    if(bool(data)):
        return {"status":400,"message":"账号已重复"}
    sql='insert into user values("{}","{}","{}","{}","{}","{}","{}","{}","{}","{}","{}")'.format(id,user,password,theme,head_icon,name,sex,birthday,Personal_signature,user,user)
    #sql1='insert into tree values("{}",0,0,0)'.format(id)
    cursor.execute(sql)
    #cursor.execute(sql1)
    conn.commit()
    return user_success

#发布帖子
@app.route('/fabu', methods=['POST'])
def haha():
    user_token=request.values.get('user_token')
    user_data=test(user_token)
    if user_data['state']==False:
        return user_err
    text=request.values.get("text")
    heart=request.values.get("heart")
    img_list=request.values.get("img_list")
    times=str(math.floor(time.time()))
    diary_id="#"+user_data['id']+times
    sql='insert into content values ("{}","{}","{}","{}","{}","{}")'.format(diary_id,
        user_data['id'],text,img_list,heart,times)
    cursor.execute(sql)
    conn.commit()
    return {"status": 200, "data": {}, "message": "发布成功"}


@app.route('/change_pwd',methods=['POST'])
def change_pwd():
    pwd=request.values.get('pwd')
    user_id=request.values.get("id")
    sql='update user set password = "{}" where id="{}"'.format(pwd,user_id)
    try:
        cursor.execute(sql)
        conn.commit()
        return "修改成功"
    except Exception as e:
        print(e)
        return "修改失败"

@app.route('/getDiary',methods=['POST'])
def otherDiary():
        user_token = request.values.get('user_token')
        page = (int(request.values.get("page"))-1)*10
        num = request.values.get("limit")
        user_data = test(user_token)
        type= request.values.get("type") #我的=me 所有=all 收藏=collect
        if user_data['state'] == False:
            return user_err
        user_id=user_data['id']
        if(type=="all"):
            sql = 'select * from ((select * from (select * from (select * from content) as u left outer join (select diary_id from love_diary where user_id="{}") as l on u.id=l.diary_id order by time desc) as a left outer join (select diary_id as d1 from collect_diary where user_id="{}") as b on a.id=b.d1 order by time desc limit {},{}) as c left outer join (select name,id,head_icon from user) as d on c.diary_master=d.id)'.format(user_id,user_id,page,num)
        elif(type == "me"):
            sql = 'select * from ((select * from (select * from (select * from content where diary_master="{}") as u left outer join (select diary_id from love_diary where user_id="{}") as l on u.id=l.diary_id order by time desc) as a left outer join (select diary_id as d1 from collect_diary where user_id="{}") as b on a.id=b.d1 order by time desc limit {},{}) as c left outer join (select name,id,head_icon from user) as d on c.diary_master=d.id)'.format(user_id,user_id, user_id, page, num)
        elif (type == "collect"):
            sql = 'select * from ((select * from (select * from (select * from content) as u left outer join (select diary_id from love_diary where user_id="{}") as l on u.id=l.diary_id) as a right outer join (select diary_id as d1 from collect_diary where user_id="{}") as b on a.id=b.d1 ) as c left outer join (select name,id,head_icon from user) as d on c.diary_master=d.id) order by time desc limit {},{}'.format(user_id,user_id,page,num)
        print(sql)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        data = cursor.fetchall()
        if (len(data) == 0):
            return {"data": [], "status": 200,"message":"暂无数据"}
        if data:
            pass
        else:
            return {"status":400}

        list1 = []
        for i in data:
            dict1 = {}
            dict1['id'] = i[0]
            dict1['diary_master'] = i[1]
            dict1['text'] = i[2]
            if bool(i[3]) :
                dict1['img'] = i[3].split("|")
            else:
                dict1['img']=""
            dict1['mood'] = i[4]
            dict1['time'] = i[5]
            if i[6]:

                dict1['love'] = 1
            else:
                dict1['love'] = 0
            if i[7]:

                dict1['collect'] = 1
            else:
                dict1['collect'] = 0
            dict1['name'] = i[8]
            dict1['show']=0
            dict1['head_icon']=i[10]
            list1.append(dict1)
        return {"data":list1,"status":200}
#点赞
@app.route('/add_love',methods=['POST'])
def addlove():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    diary_id = request.values.get('diary_id')
    user_id = user_data['id']
    sql = "select * from love_diary where diary_id='{}' and user_id = '{}'".format(diary_id, user_id)
    print(sql)
    conn.ping()
    cursor.execute(sql)
    data = cursor.fetchall()
    id = diary_id + 'collect' + user_id
    if (data):
        sql = "delete from love_diary where diary_id='{}' and user_id = '{}'".format(diary_id, user_id)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        conn.commit()
        print('删除')
    else:
        sql="insert into love_diary (diary_id,user_id) values('{}','{}')".format(diary_id,user_id)
        print(sql)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        conn.commit()
        print('添加')
    return user_success
#收藏
@app.route('/collect',methods=['POST'])
def collect():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    diary_id=request.values.get('diary_id')
    user_id=user_data['id']
    sql="select * from collect_diary where diary_id='{}' and user_id = '{}'".format(diary_id,user_id)
    print(sql)
    conn.ping()
    cursor.execute(sql)
    data = cursor.fetchall()
    id=diary_id+'collect'+user_id
    if(data):
        sql = "delete from collect_diary where diary_id='{}' and user_id = '{}'".format(diary_id,user_id)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        conn.commit()
        print('删除')
    else:
        sql="insert into collect_diary (diary_id,user_id,NO) values('{}','{}','{}')".format(diary_id,user_id,id)
        print(sql)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        conn.commit()
        print('添加')
    return user_success
#删除喜欢
@app.route('/del_love',methods=['POST'])
def dellove():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    diary_id=request.values.get('diary_id')
    user_id=user_data['id']
    sql="delete from love_diary where diary_id='{}' and user_id='{}'".format(diary_id,user_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    return user_success
#删除帖子
@app.route('/del_diary',methods=['POST'])
def del_diary():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    diary_master=request.values.get('diary_master')
    diary_id=request.values.get('id')
    sql = "delete from content where id='{}' and diary_master='{}'".format(diary_id,diary_master)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    sql='delete from love_diary where diary_id='+diary_id
    cursor.execute(sql)
    conn.commit()
    return user_success
#获取评论
@app.route("/get_pinglun",methods=['POST'])
def get_pinglun():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    diary_id=request.values.get("id")
    page=int(request.values.get("page"))-1
    limit =int(request.values.get("limit"))
    #sql='select * from pinglun where diary_id = "{}" order by time,parent_id desc'.format(diary_id)
    sql="select a.*,b.name,b.head_icon from ((select * from pinglun where diary_id = '{}') as a inner join (user as b) on a.pinglun_user_id=b.id) order by time desc limit {},{}".format(diary_id,page,limit)
    print(sql)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    data=cursor.fetchall()
    list1=[]
    for i in data:
        dict1={}
        dict1['text']=i[1]
        dict1['pinglun_id']=i[2]
        dict1['parent_id']=i[3]
        dict1['time'] = i[4]
        dict1['pinglun_user_id']=i[7]
        dict1['pinglun_user_name']=i[8]
        dict1['head_icon'] = i[9]
        list1.append(dict1)
    return {'data':list1,'status':200}
#发布评论
@app.route('/huifu_pinglun',methods=['POST'])
def huifu_pinglun():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    times = math.floor(time.time())
    diary_id=request.values.get('diary_id')
    text=request.values.get('text')
    pinglun_id='#'+str(times)+'pinglun'
    user_id=user_data['id']
    user_name=""
    sql='insert into pinglun (diary_id,text,pinglun_id,parent_id,time,user_name,huifu_name,pinglun_user_id) values("{}","{}","{}","{}","{}","{}","{}","{}")'.format(diary_id,text,pinglun_id,pinglun_id,times,user_name,user_name,user_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    return user_success
#评论别人的评论
@app.route('/huifu_other_pinglun',methods=['POST'])
def huifu_other_pinglun():
    times = math.floor(time.time())
    diary_id=request.values.get('diary_id')
    text=request.values.get('text')
    pinglun_id='#'+str(times)+'pinglun'
    parent_id=request.values.get("parent_id")
    user_name=request.values.get('user_name')
    huifu_name = request.values.get('huifu_name')
    sql='insert into pinglun (diary_id,text,pinglun_id,parent_id,time,user_name,huifu_name) values("{}","{}","{}","{}","{}","{}","{}")'.format(diary_id,text,pinglun_id,parent_id,times,user_name,huifu_name)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    return '回复成功'
@app.route('/del_pinglun',methods=['POST'])
def del_pinglun():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    pinglun_id=request.values.get('pinglun_id')
    parent_id=request.values.get('parent_id')
    sql="delete from pinglun where parent_id='{}' and time>=(select a.time from((select time from pinglun where pinglun_id='{}' and parent_id='{}') a))".format(parent_id,pinglun_id,parent_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    # lock.release()
    conn.commit()
    return "删除成功"
@app.route('/edit_theme',methods=['post'])
def deit_theme():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    theme=request.values.get('theme')
    user_id=request.values.get('user_id')
    sql='update user set theme = "{}" where id= "{}"'.format(theme,user_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    return "修改成功"
@app.route('/edit_head_icon',methods=['POST'])
def edit_head_icon():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    head_icon=request.values.get('head_icon').split(',')[1]
    id=request.values.get('user_id')
    data =str(math.floor(time.time()))
    img =  base64.b64decode(head_icon)
    os.makedirs('head_icon/'+id, exist_ok=True)
    file = open('head_icon/'+id +'/'+ data + '.jpeg', 'wb')
    # with open(os.path.join(date,"{}-{}.jpeg".format(times,i)),"wb") as f:
    file.write(img)
    #head_icon="http://127.0.0.1:1000/head_icon/"+id +'/'+data+'.jpeg'
    img_name = "http://www.5jiahui.xyz/api/head_icon/{}/{}.jpeg".format(id,data)
    # img_list.append(img_name)
    print(img_name)

    sql='update user set head_icon="{}" where id = "{}";'.format(img_name,id)
    print(sql)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    return "修改头像成功"
@app.route('/get_mylove_diary',methods=['POST'])
def get_mylove_diary():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    user_id=request.values.get('user_id')
    sql='select a.* from content as a inner join (select * from love_diary where user_id="{}") as b where a.id=b.diary_id'.format(user_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    data=cursor.fetchall()
    list1 = []
    for i in data:
        dict1 = {}
        dict1['id'] = i[0]
        dict1['diary_master'] = i[1]
        dict1['text'] = i[2]
        if bool(i[3]):
            dict1['img'] = i[3].split("|")
        else:
            dict1['img'] = ""
        dict1['mood'] = i[4]
        dict1['time'] = i[5]
        dict1['love'] = 1
        dict1['show'] = 0
        list1.append(dict1)
    return {"data": list1}
@app.route('/change_my_date',methods=['POST'])
def change_my_date():
    user_token = request.values.get('user_token')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    # headIcon: "",
    # nickname: "123",
    # phone: "",
    # signature: "",
    # birthday: "",
    # sex: ""
    user_id=user_data['id']
    headIcon=request.values.get('headIcon')
    name=request.values.get('nickname')
    phone=request.values.get('phone')
    sex=request.values.get('sex')
    birthday=request.values.get('birthday')
    Personal_signature=request.values.get('signature')
    sql='update user set name="{}",sex="{}",birthday="{}",Personal_signature="{}",head_icon="{}",phone="{}" where id ="{}" '.format(name,sex,birthday,Personal_signature,headIcon,phone,user_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    return user_success
@app.route('/tree',methods=['POST'])
def tree():
    times=math.floor(time.time())
    user_id=request.values.get("user_id")
    sql='select * from tree where user_id="{}"'.format(user_id)
    conn.ping(reconnect=True)
    cursor.execute(sql)
    data=cursor.fetchone()
    print(data)
    dict1={}
    dict1['tree_power']=data[1]
    if(times-data[2]>=8000):
        dict1['water_time']=True
    else:
        dict1['water_time'] = False
    if (times - data[3] >= 8000):
        dict1['huafei_time'] = True
    else:
        dict1['huafei_time'] = False
    return {'data':dict1}
@app.route('/update_tree_time',methods=['post'])
def update_tree():
    power=request.values.get('power')
    id=request.values.get("id")
    times=math.floor(time.time())
    type=request.values.get('type')
    sql='update tree set {} ={},tree_power={} where user_id="{}" '.format(type,times,power,id)
    print(sql)
    conn.ping(reconnect=True)
    try:
        cursor.execute(sql)
        conn.commit()
        return "change"
    except Exception as e:
        conn.rollback()
        print("error", e)
        return "error"
@app.route('/get_store',methods=['GET'])
def get_store():
    sql = 'select * from store order by id desc;'
    cursor.execute(sql)
    new_store = cursor.fetchall()
    new_store_list = []
    other_store_list = []
    n = 0
    for i in new_store:
        d = {}
        d['img'] = i[0]
        d['name'] = i[1]
        d['id'] = i[2]
        d['price'] = i[3]

        if (n < 4):
            new_store_list.append(d)
            n += 1
            continue
        other_store_list.append(d)
        n += 1
    return {"new_store_list": new_store_list, "other_store_list": other_store_list}
@app.route('/add_colthes_item',methods=['POST'])
def add_colthes_item():
    img=request.values.get('img').split(',')[1]
    id =str(math.floor(time.time()))
    img = base64.b64decode(img)
    os.makedirs('clothes_img/', exist_ok=True)
    file = open('clothes_img/' + id+ '.jpeg', 'wb')
    file.write(img)
    imgs='http://www.5jiahui.xyz/api/clothes/'+id+'.jpeg'
    name=request.values.get("name")
    colors=request.values.get("color")
    times=request.values.get("time")
    address=request.values.get("address")
    state=request.values.get("state")
    remarks=request.values.get("remarks")
    try:
        sql='insert into clothes_system values ("{}","{}","{}","{}","{}","{}","{}","{}" )'.format(id,imgs,name,colors,times,address,state,remarks)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        conn.commit()
        return "提交成功"
    except:
        conn.rollback()
        return  "提交失败"
@app.route('/update_colthes_item',methods=['POST'])
def update_colthes_item():
    id = request.values.get('id')
    name=request.values.get("name")
    colors=request.values.get("color")
    times=request.values.get("time")
    address=request.values.get("address")
    remarks=request.values.get("remarks")
    try:
        sql='update clothes_system set name="{}",color="{}",time="{}",address="{}",remarks="{}" where id="{}"'.format(name,colors,times,address,remarks,id)
        conn.ping(reconnect=True)
        cursor.execute(sql)
        conn.commit()
        return "修改成功"
    except:
        conn.rollback()
        return  "修改失败"
@app.route("/get_colthes_list",methods=['GET'])
def get_colthes_list():
    sql='select * from clothes_system'
    conn.ping(reconnect=True)
    cursor.execute(sql)
    dates=cursor.fetchall()
    list1=[]
    for i in dates:
        dict1={}
        dict1['id']=i[0]
        dict1['img'] = i[1]
        dict1['name'] = i[2]
        dict1['color'] = i[3]
        dict1['time'] = i[4]
        dict1['address'] = i[5]
        dict1['state'] = i[6]
        dict1['remarks'] = i[7]
        list1.append(dict1)
    print(list1)
    return {"data":list1}
@app.route("/search_clothes",methods=['POST'])
def search_clothes():
    time=request.values.get("time")
    keyword=request.values.get("keyword")
    state=request.values.get('state')
    sql='select * from clothes_system where name like "%{}%" and time like "%{}%" and state like "%{}%";'.format(keyword,time,state)
    cursor.execute(sql)
    data=cursor.fetchall()
    if(bool(data)):
        list1 = []
        for i in data:
            dict1 = {}
            dict1['id'] = i[0]
            dict1['img'] = i[1]
            dict1['name'] = i[2]
            dict1['color'] = i[3]
            dict1['time'] = i[4]
            dict1['address'] = i[5]
            dict1['state'] = i[6]
            dict1['remarks'] = i[7]
            list1.append(dict1)
        print(list1)
        return {"data": list1}
    else:
        return {"data": "没得数据"}
@app.route('/del_clothes',methods=['POST'])
def del_clothes():
    id=request.values.get('id')
    sql='delete from clothes_system where id ="{}"'.format(id)
    cursor.execute(sql)
    conn.commit()
    return "删除成功"
# 反馈
@app.route('/faceback',methods=['POST'])
def faceback():
    user_token = request.values.get('user_token')
    text=request.values.get('text')
    img=request.values.get('img')
    user_data = test(user_token)
    if user_data['state'] == False:
        return user_err
    id = user_data['id']
    times=math.floor(time.time())
    faceback_id= str(times)+"user"+id
    sql='insert into faceback values ("{}","{}","{}","{}")'.format(faceback_id,text,img,id)
    cursor.execute(sql)
    conn.commit()
    return user_success
@app.route('/upload',methods=['POST'])
def upload():
    images = request.files.get('img')
    print(images)
    times = str(math.floor(time.time()))
    path='./img/'+times+images.filename
    isExists = os.path.exists('./img')
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs('./img')
    images.save(path)
    # image_data = np.fromstring(img, np.uint8)
    # image_data = cv2.imdecode(image_data, cv2.IMREAD_COLOR)
    # cv2.imwrite('/root/01.png', image_data)
    # print(image_data)
    return {'url':img_root+times+images.filename}

if __name__ == '__main__':
    app.run(port=5000)
